package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.HttpClient;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.ApplicationModule;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/web/admin/dashboard")
public class DashBoardManageAction {

    @Autowired
    private ApplicationModuleBiz applicationModuleBiz;
    @Autowired
    private PersonnnelOrganizationBiz personnnelOrganizationBiz;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private PersonnelBiz personnelBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    /**
     * PCDashBoard工单列表
     */
    @RequestMapping("/orderInfo")
    @ResponseBody
    public ResultDto orderInfo(@RequestBody Map<String,Object> map) {
        if(map == null || map.size() == 0 ){
            return ResultUtil.error("参数错误");
        }
        Integer startIndex = Integer.valueOf(StringConverters.null2String(map.get("pageIndex")));
        Integer rows = Integer.valueOf(StringConverters.null2String(map.get("pageSize")));
        return personnnelOrganizationBiz.orderInfo(startIndex, rows);
    }

    /**
     * PCDashBoard近7天工单数 近30天工单数
     */
    @RequestMapping("/orderNum")
    @ResponseBody
    public ResultDto orderNum(@RequestBody Map<String,Object> map) {
        return personnnelOrganizationBiz.orderNum(StringConverters.null2String(map.get("dayNum")));
    }


    @RequestMapping("/applicationModuleInfo")
    @ResponseBody
    public ResultDto applicationModuleInfo(){
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (null == sessionEnterprise || null == systemUser) {
            return ResultUtil.error("请重新登陆");
        }

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("enterpriseId", sessionEnterprise.getId());
        dataMap.put("systemUserId", systemUser.getId());

        String repairOrderUrl = Configuration.getConfigurationByName("hostUrl") + "/web/admin/repairOrder/countScore.action";
        String maintainOrderUrl = Configuration.getConfigurationByName("hostUrl") + "/web/admin/maintainOrder/countScore.action";
        String inspectionOrderUrl = Configuration.getConfigurationByName("hostUrl") + "/web/admin/inspectionOrder/countScore.action";


        JSONObject result = new JSONObject();
        QueryParam queryParam1 = new QueryParam();
        queryParam1.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        List<ApplicationModule> applicationModules = applicationModuleBiz.findList(queryParam1);
        for (ApplicationModule x : applicationModules) {
            if("REPAIR".equals(x.getRemark())){
                JSONObject repairInfo = JSONObject.parseObject(HttpClient.doPost(repairOrderUrl, dataMap));
                result.put("repairInfo",repairInfo);
            }else if("MAINTAIN".equals(x.getRemark())){
                JSONObject maintainInfo = JSONObject.parseObject(HttpClient.doPost(maintainOrderUrl, dataMap));
                result.put("maintainInfo",maintainInfo);
            }else if("INSPECTION".equals(x.getRemark())) {
                JSONObject inspectioInfo = JSONObject.parseObject(HttpClient.doPost(inspectionOrderUrl, dataMap));
                result.put("inspectioInfo", inspectioInfo);
            }
        }

        JSONObject data = new JSONObject();
        data.put("totalEnterpriseCount",0);
        data.put("newEnterpriseCount",0);
        data.put("totalPeopleCount",0);
        data.put("newPeopleCount",0);
        data.put("totalFacilityCount",0);
        data.put("newFacilityCount",0);
        String todayString = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getBeginOfDay(new Date()));
        String childrenIds = enterpriseBiz.childrenIds(sessionEnterprise.getId()+"");
        //计算企业数
        data.put("totalEnterpriseCount",enterpriseBiz.childrenCount(sessionEnterprise.getId()+"",""));
        //计算当天新增企业数
        data.put("newEnterpriseCount",enterpriseBiz.childrenCount(sessionEnterprise.getId()+"",todayString));
        //计算运维人员数
        data.put("totalPeopleCount",personnelBiz.personCount(childrenIds,""));
        //计算当天新增运维人员数
        data.put("newPeopleCount",personnelBiz.personCount(childrenIds,todayString));
        //计算设备数
        data.put("totalFacilityCount",facilityBiz.facilityCount(childrenIds,""));
        //计算当天新增设备数
        data.put("newFacilityCount",facilityBiz.facilityCount(childrenIds,todayString));
        result.put("enterpriseInfo",data);
        return  ResultUtil.success(result);
    }

    /**
     * 专业统计
     */
    @RequestMapping(value = "/groupByRootCat")
    @ResponseBody
    public ResultDto groupByRootCat(){
        JSONObject data = new JSONObject();
        JSONArray rows = new JSONArray();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if(enterprise==null){
            data.put("rows",rows);
            return ResultUtil.success(data);
        }
        rows = facilityBiz.groupByRootCat(enterpriseBiz.childrenIds(enterprise.getId()+""));
        data.put("rows",rows);
        return ResultUtil.success(data);
    }

    /**
     * 运维人员统计
     */
    @RequestMapping(value = "/basicStatistic")
    @ResponseBody
    public ResultDto basicStatistic(){
        JSONObject data = new JSONObject();
        data.put("totalEnterpriseCount",0);
        data.put("newEnterpriseCount",0);
        data.put("totalPeopleCount",0);
        data.put("newPeopleCount",0);
        data.put("totalFacilityCount",0);
        data.put("newFacilityCount",0);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if(enterprise==null){
            return ResultUtil.success(data);
        }
        String todayString = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getBeginOfDay(new Date()));
        String childrenIds = enterpriseBiz.childrenIds(enterprise.getId()+"");
        //计算企业数
        data.put("totalEnterpriseCount",enterpriseBiz.childrenCount(enterprise.getId()+"",""));
        //计算当天新增企业数
        data.put("newEnterpriseCount",enterpriseBiz.childrenCount(enterprise.getId()+"",todayString));
        //计算运维人员数
        data.put("totalPeopleCount",personnelBiz.personCount(childrenIds,""));
        //计算当天新增运维人员数
        data.put("newPeopleCount",personnelBiz.personCount(childrenIds,todayString));
        //计算设备数
        data.put("totalFacilityCount",facilityBiz.facilityCount(childrenIds,""));
        //计算当天新增设备数
        data.put("newFacilityCount",facilityBiz.facilityCount(childrenIds,todayString));

        return ResultUtil.success(data);
    }
    /**
     * 维护保养工单数量统计
     */
    @RequestMapping(value = "/maintainReportNum")
    @ResponseBody
    public ResultDto maintainReportNum(){
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if(enterprise==null){
            return ResultUtil.error();
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("enterpriseId",enterprise.getId()+"");
        String maintainDataUrl = Configuration.getConfigurationByName("hostUrl") + "maintainCharts/maintainReportNum.action";
        JSONObject maintainData = JSONObject.parseObject(HttpClient.doPost(maintainDataUrl, dataMap));
        return ResultUtil.success(maintainData);
    }
    /**
     * 巡检工单数量统计
     */
    @RequestMapping(value = "/inspectionReportNum")
    @ResponseBody
    public ResultDto inspectionReportNum(){
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if(enterprise==null){
            return ResultUtil.error();
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("enterpriseId",enterprise.getId()+"");
        String inspectionDataUrl = Configuration.getConfigurationByName("hostUrl") + "inspectionCharts/inspectionReportNum.action";
        JSONObject inspectionData = JSONObject.parseObject(HttpClient.doPost(inspectionDataUrl, dataMap));
        return ResultUtil.success(inspectionData);
    }

    /**
     * 作业人员(专业)工作完成情况统计
     * type:day/month 默认day
     */
    @RequestMapping(value = "/completePercent")
    @ResponseBody
    public JSONObject completePercent(@RequestBody Map<String,Object> map){
        JSONObject result = new JSONObject();
        Map<String, Object> dataMap = new HashMap<>();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if(enterprise!=null){
            dataMap.put("enterpriseId",enterprise.getId()+"");
        }else{
            dataMap.put("enterpriseId",null);
        }
        if(map == null || map.size() == 0 ){
            dataMap.put("type","day");
        }else{
            String type = StringConverters.null2String(map.get("type"));
            if(!"month".equals(type)){
                dataMap.put("type","day");
            }else{
                dataMap.put("type","month");
            }
        }
        String url = Configuration.getConfigurationByName("hostUrl") + "/inspectionDashboardReport/completePercent.action";
        result =  JSONObject.parseObject(HttpClient.doPost(url, dataMap));
        return result;
    }

    /**
     * 维修工单(今日)
     */
    @RequestMapping(value = "/repairOrderCount")
    @ResponseBody
    public JSONObject repairOrderCount(){
        JSONObject result = new JSONObject();
        Map<String, Object> dataMap = new HashMap<>();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if(enterprise!=null){
            dataMap.put("enterpriseId",enterprise.getId()+"");
        }else{
            dataMap.put("enterpriseId",null);
        }
        String url = Configuration.getConfigurationByName("hostUrl") + "/repairDashboardReport/repairOrderCount.action";
        result =  JSONObject.parseObject(HttpClient.doPost(url, dataMap));
        return result;
    }

    /**
     * 设备故障发生次数TOP10
     */
    @RequestMapping(value = "/repairTop10")
    @ResponseBody
    public JSONObject repairTop10(@RequestBody Map<String,Object> map){
        JSONObject result = new JSONObject();
        Map<String, Object> dataMap = new HashMap<>();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if(enterprise!=null){
            dataMap.put("enterpriseId",enterprise.getId()+"");
        }else{
            dataMap.put("enterpriseId",null);
        }
        if(map == null || map.size() == 0 ){
            dataMap.put("type","day");
        }else{
            String type = StringConverters.null2String(map.get("type"));
            if(!"month".equals(type)){
                dataMap.put("type","day");
            }else{
                dataMap.put("type","month");
            }
        }
        String url = Configuration.getConfigurationByName("hostUrl") + "/repairDashboardReport/repairTop10.action";
        result =  JSONObject.parseObject(HttpClient.doPost(url, dataMap));
        return result;
    }

    /**
     * 设施设备运行状态
     */
    @RequestMapping(value = "/facilityStatus")
    @ResponseBody
    public ResultDto facilityStatus(){
        JSONObject data = new JSONObject();
        Map<String, Object> dataMap = new HashMap<>();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        data.put("maintainCount",0);
        data.put("inspectionCount",0);
        data.put("repairCount",0);
        data.put("normalCount",0);
        if(enterprise==null){
            return ResultUtil.success(data);
        }
        dataMap.put("enterpriseId",enterprise.getId()+"");
        //正在维修中的设备
        String repairUrl = Configuration.getConfigurationByName("hostUrl") + "/repairDashboardReport/repairFacilityCount.action";
        JSONObject repairJson = JSONObject.parseObject(HttpClient.doPost(repairUrl, dataMap));
        JSONArray repairRows = repairJson.getJSONArray("rows");
        Map<String,String> repairMap = new HashMap<>();
        if(repairRows.size()>0){
            data.put("repairCount",repairRows.size());
            for (int i = 0; i < repairRows.size(); i++) {
                repairMap.put(repairRows.getJSONObject(i).getString("facilityId"),"");
            }
        }
        //正在维保中的设备
        String maintainUrl = Configuration.getConfigurationByName("hostUrl") + "/maintainDashboardReport/maintainFacilityCount.action";
        JSONObject maintainJson = JSONObject.parseObject(HttpClient.doPost(maintainUrl, dataMap));
        JSONArray maintainRows = maintainJson.getJSONArray("rows");
        Map<String,String> maintainMap = new HashMap<>();
        if(maintainRows.size()>0){
            data.put("maintainCount",maintainRows.size());
            for (int i = 0; i < maintainRows.size(); i++) {
                maintainMap.put(maintainRows.getJSONObject(i).getString("facilityId"),"");
            }
        }
        //正在巡检中的设备
        String inspectionUrl = Configuration.getConfigurationByName("hostUrl") + "/inspectionDashboardReport/inspectionFacilityCount.action";
        JSONObject inspectionJson = JSONObject.parseObject(HttpClient.doPost(inspectionUrl, dataMap));
        JSONArray inspectionRows = inspectionJson.getJSONArray("rows");
        Map<String,String> inspectionMap = new HashMap<>();
        if(inspectionRows.size()>0){
            data.put("inspectionCount",inspectionRows.size());
            for (int i = 0; i < inspectionRows.size(); i++) {
                inspectionMap.put(inspectionRows.getJSONObject(i).getString("facilityId"),"");
            }
        }



        //正常设备
        String childrenIds = enterpriseBiz.childrenIds(enterprise.getId()+"");
        int normalCount = facilityBiz.facilityCount(childrenIds,"");
        repairMap.putAll(maintainMap);
        repairMap.putAll(inspectionMap);
        if(repairMap.size()>0){
            normalCount = normalCount-repairMap.size();
        }
        data.put("normalCount",normalCount);
        return ResultUtil.success(data);
    }

    /**
     * 分区域维修完成率
     */
    @RequestMapping(value = "/areaPercent")
    @ResponseBody
    public JSONObject areaPercent(){
        JSONObject result;
        Map<String, Object> dataMap = new HashMap<>();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if(enterprise!=null){
            dataMap.put("enterpriseId",enterprise.getId()+"");
        }else{
            dataMap.put("enterpriseId",null);
        }
        String url = Configuration.getConfigurationByName("hostUrl") + "/repairDashboardReport/areaPercent.action";
        result =  JSONObject.parseObject(HttpClient.doPost(url, dataMap));
        return result;
    }
}
